import { Injectable, Logger } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";

import { JwtPayloadVO } from "@/core/vo/jwt-payload.vo";

import { jwtConstants } from "../constants";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    private readonly logger = new Logger(JwtStrategy.name);
    constructor() {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // 从请求头中获取token。Authorization: Bearer xxx
            ignoreExpiration: false,
            secretOrKey: jwtConstants.secret
        });
    }

    async validate(payload: JwtPayloadVO) {
        // TODO: 区分Token过期，予以不同的响应提示。当前过期的情况，响应为401和不携带token是一样的。
        // payload 为解析 jwt 后得到的数据
        // if (process.env.NODE_ENV === RuntimeEnv.DEV) console.log("jwt payload", payload);
        this.logger.debug(`jwt payload: ${JSON.stringify(payload)}`);
        // 返回值将作为 req.user 的值
        return payload;
    }
}
